package com.zjs.express.controller;

import com.zjs.express.bean.Admin;
import com.zjs.express.common.ResultModel;
import com.zjs.express.mvc.annotation.RequestMapping;
import com.zjs.express.mvc.annotation.ResponseBody;
import com.zjs.express.service.AdminService;
import com.zjs.express.service.impl.AdminServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminController {
    private AdminService adminService = new AdminServiceImpl();

    @RequestMapping(value = "/admin/toLogin.do")
    public String toLogin() {
        //重定向登录界面
        return "redirect:admin/login";
    }

    @RequestMapping(value = "/admin/login.do")
    @ResponseBody
    public ResultModel login(HttpServletRequest request, HttpServletResponse response) {
        //获取用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取ip
        String ip = "";
        // 首先尝试从 X-Forwarded-For 请求头获取 IP 地址
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader != null) {
            // X-Forwarded-For 头可能包含多个 IP 地址，用逗号分隔，第一个通常是客户端的 IP
            ip = xfHeader.split(",")[0].trim();
        }
        // 如果 X-Forwarded-For 头不存在，则使用 getRemoteAddr() 方法
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }
        ResultModel resultModel = adminService.login(username, password, ip);
        if (resultModel != null && resultModel.isSuccess()) {
            //将用户信息存到session
            Admin admin = (Admin) resultModel.getRows();
            request.getSession().setAttribute("admin", admin);
        }
        return resultModel;
    }

    /**
     * 获取session进行登陆人显示
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/getSession.do")
    @ResponseBody
    public ResultModel getSession(HttpServletRequest request, HttpServletResponse response) {
        //获取session
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        return ResultModel.success(admin);
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/admin/loginOut.do")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        //删除session
        request.getSession().invalidate();
        return "/admin/toLogin.do";
    }
}
